package com.example.ranl_safeapi.Controller;

import com.example.ranl_safeapi.AOP.ApiTrafficMonitorAspect;
import com.example.ranl_safeapi.Entity.PageResult;
import com.example.ranl_safeapi.Entity.Student;
import com.example.ranl_safeapi.Service.StudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/api")
public class StudentController {

    private static final Logger LOGGER = LoggerFactory.getLogger(StudentController.class);

    @Autowired
    private StudentService studentService;

    @Autowired
    private ApiTrafficMonitorAspect apiTrafficMonitorAspect;

    private static final int MAX_QPS = 10; // 最大QPS阈值
    private static final AtomicInteger CURRENT_QPS = new AtomicInteger(0); // 当前QPS

    //按照名字查询
    @GetMapping("/name")
    public PageResult<Student> getUserList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String namePrefix
    ) {

        String logId = UUID.randomUUID().toString(); // 生成logID

        try {
            // QPS保护
            if (CURRENT_QPS.getAndIncrement() > MAX_QPS) {
                LOGGER.warn("[{}] QPS limit exceeded. Rejecting request.", logId);
                return null; // 或者抛出自定义异常
            }

            //入参记录
            LOGGER.info("[{}] Request received for /api/name with parameters: pageNum={}, pageSize={}, namePrefix={}, startTime={}", logId, pageNum, pageSize, namePrefix, System.currentTimeMillis());

            long startTime = System.currentTimeMillis();

//            // 获取每秒请求量
//            int requestCountPerSecond = apiTrafficMonitorAspect.getRequestCountPerSecond();
//            System.out.println("Request count per second for /api/name: " + requestCountPerSecond);
//            LOGGER.info("[{}] Request count per second: {}", logId, requestCountPerSecond);

            // 获取每条请求的平均响应时间
            Map<String, Double> averageResponseTimeMap = apiTrafficMonitorAspect.getAverageResponseTime();
            for (Map.Entry<String, Double> entry : averageResponseTimeMap.entrySet()) {
                LOGGER.info("[{}] Request method: {}, average response time: {}ms", logId, entry.getKey(), entry.getValue());
            }

            long endTime = System.currentTimeMillis();
            LOGGER.info("[{}] Request for /api/name completed in {}ms", logId, endTime - startTime);

            // 对pageSize进行范围判断
            if (pageSize < 1 || pageSize > 1000) {
                throw new IllegalArgumentException("Page size must be between 1 and 1000");
            }

            // 设置默认值
            pageNum = Math.max(pageNum, 1); // pageNum至少为1

            PageResult<Student> pageResult = studentService.findByPrefix(pageNum, pageSize, namePrefix);

            // 记录出参
            LOGGER.info("[{}] Response: {}, endTime={}", logId, pageResult, System.currentTimeMillis());

            return pageResult;
        }finally {
            CURRENT_QPS.decrementAndGet();
        }
    }

    //按照生日查询
    @GetMapping("/birth")
    public PageResult<Student> getUserList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startday,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date finalday
    ){
        String logId = UUID.randomUUID().toString(); // 生成logID

        try {
            // QPS保护
            if (CURRENT_QPS.getAndIncrement() > MAX_QPS) {
                LOGGER.warn("[{}] QPS limit exceeded. Rejecting request.", logId);
                return null; // 或者抛出自定义异常
            }

            LOGGER.info("[{}] Request received for /api/birth with parameters: pageNum={}, pageSize={}, startday={}, finalday={}, startTime={}", logId, pageNum, pageSize, startday, finalday, System.currentTimeMillis());

            long startTime = System.currentTimeMillis();

//            // 获取每秒请求量
//            int requestCountPerSecond = apiTrafficMonitorAspect.getRequestCountPerSecond();
//            System.out.println("Request count per second for /api/birth: " + requestCountPerSecond);
//            LOGGER.info("[{}] Request count per second: {}", logId, requestCountPerSecond);

            // 获取每条请求的平均响应时间
            Map<String, Double> averageResponseTimeMap = apiTrafficMonitorAspect.getAverageResponseTime();
            for (Map.Entry<String, Double> entry : averageResponseTimeMap.entrySet()) {
                LOGGER.info("[{}] Request method: {}, average response time: {}ms", logId, entry.getKey(), entry.getValue());
            }

            // 对pageSize进行范围判断
            if (pageSize < 1 || pageSize > 1000) {
                throw new IllegalArgumentException("Page size must be between 1 and 1000");
            }

            // 设置默认值
            pageNum = Math.max(pageNum, 1); // pageNum至少为1

            // 对日期格式进行验证
            if (startday != null && finalday != null && startday.after(finalday)) {
                throw new IllegalArgumentException("Start date must be before final date");
            }

            long endTime = System.currentTimeMillis();
            LOGGER.info("[{}] Request for /api/birth completed in {}ms", logId, endTime - startTime);

            PageResult<Student> pageResult = studentService.findByBirth(pageNum, pageSize, startday, finalday);

            // 记录出参
            LOGGER.info("[{}] Response: {}, endTime={}", logId, pageResult, System.currentTimeMillis());

            return pageResult;
        }finally {
            CURRENT_QPS.decrementAndGet();
        }

    }

}
